package com.mobile.validatecode;

import com.itheima.common.constant.MessageConstant;
import com.itheima.common.constant.RedisMessageConstant;
import com.itheima.common.entity.Result;
import com.itheima.common.utils.SMSUtils;
import com.itheima.common.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachePut;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author Encounter
 * @date 2024/10/14 11:37<br/>
 * 验证码
 */
@RestController
@RequestMapping("/validatecode")
@Slf4j
public class ValidateCodeController
    {
        @Autowired
        private SMSUtils smsUtils;
        @Autowired
        private RedisTemplate redisTemplate;
        
        /**
         * 发送预约验证码
         *
         * @param telephone 电话
         * @return {@link Result }
         */
        @PostMapping("/send4Order")
        public Result send4Order(@RequestParam String telephone)
            {
                try
                    {
                        log.info("接收验证码手机号：{}", telephone);
                        //生成4位数字与字母混合验证码
                        //String code = String.valueOf(ValidateCodeUtils.generateValidateCode(4));
                        String code = ValidateCodeUtils.generateValidateCode4String(4);
                        Map<String, String> map = new HashMap<>();
                        map.put("code", code);
                        boolean isSent = smsUtils.sendMessage(smsUtils.getValidateCode(), telephone, map);
                        //判断是否发送成功
                        if (isSent)
                            {
                                //发送成功，将生成的验证码存入redis缓存并设置有效时限为5min
                                storeValidateCode(code, telephone, RedisMessageConstant.SENDTYPE_ORDER);
                                return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS, code);
                            }
                        else
                            {
                                return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
                            }
                        //将生成的验证码存入redis缓存并设置有效时限为5min
                        //storeValidateCode(code, telephone, RedisMessageConstant.SENDTYPE_ORDER);
                        //return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS, code);
                    }
                catch (Exception e)
                    {
                        //throw new RuntimeException(e);
                        return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
                    }
            }
        
        /**
         * 手机号登录发送验证码
         *
         * @param telephone 电话
         * @return {@link Result }
         */
        @GetMapping("/send4Login")
        public Result send4Login(@RequestParam String telephone)
            {
                try
                    {
                        log.info("要登陆的手机号：{}", telephone);
                        //生成4位数字与字母混合验证码
                        String code = ValidateCodeUtils.generateValidateCode4String(4);
                        Map<String, String> map = new HashMap<>();
                        map.put("code", code);
                        //判断验证码是否发送成功
                        boolean isSent = smsUtils.sendMessage(smsUtils.getValidateCode(), telephone, map);
                        if (isSent)
                            {
                                //发送成功，存储到Redis，并设置有效时限为5min
                                storeValidateCode(code, telephone, RedisMessageConstant.SENDTYPE_LOGIN);
                                return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS, code);
                            }
                        else
                            {
                                return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
                            }
                    }
                catch (Exception e)
                    {
                        //throw new RuntimeException(e);
                        return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
                    }
            }
        
        /**
         * 存储验证代码
         *
         * @param code      验证码
         * @param telephone 手机号
         * @param keyPrefix 存储前缀
         */
        private void storeValidateCode(String code, String telephone, String keyPrefix)
            {
                // 使用 keyPrefix + 手机号作为键名
                String key = keyPrefix + ":" + telephone;
                // 获取操作字符串（简单的值）类型的操作接口
                ValueOperations ops = redisTemplate.opsForValue();
                // 设置验证码到 Redis，并设置过期时间为 5 分钟（300 秒）
                ops.set(key, code, 5, TimeUnit.MINUTES);
            }
    }
